package com.xiangyouhui.base_project.interceptor;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

public class CommonRequestInterceptor implements HandlerInterceptor {
    private static final Logger logger = LogManager.getLogger();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        Map<String, String[]> params = request.getParameterMap();
        StringBuilder logSB = new StringBuilder();

        logSB.append(request.getRequestURI())
                .append('?');
        for (String key : params.keySet()) {
            logSB.append(key)
                    .append('=')
                    .append(params.get(key)[0])
                    .append('&');
        }
        if (logSB.charAt(logSB.length() - 1) == '&') {
            logSB.deleteCharAt(logSB.length() - 1);
        }
        logger.info(logSB.toString());

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
